package concurrency.volatiletrick;

/**
 * Created by Tzachi on 19/10/2014.
 */
public class Performance {
    static class Counter {
        volatile long counter1;
        /*
            padding is needed to enhance performce since otherwise both volatile counters exist in the same
            physical block in memory
         */
        long q1, q2, q3, q4, q5, q6, q7, q8;
        volatile long counter2;
    }

    static Counter counter = new Counter();

    static class Worker implements Runnable {
        private static final int INT = Integer.MAX_VALUE / 8;
        private final boolean isCounter1;

        Worker(boolean isCounter1) {
            this.isCounter1 = isCounter1;
        }

        @Override
        public void run() {
            long start = System.currentTimeMillis();
            if (isCounter1) {
                for (int i = 0; i < INT; i++) {
                    counter.counter1++;
                }
            } else {
                for (int i = 0; i < INT; i++) {
                    counter.counter2++;
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("took: " + (end - start) + " " + counter.counter1 + counter.counter2);
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new Worker(true));
        Thread t2 = new Thread(new Worker(false));
        t1.start();
        t2.start();
    }
}
